<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ .title }}</title>
    <link href="https://cdn.jsdelivr.net/npm/daisyui@4.12.10/dist/full.min.css" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body class="bg-gray-50">
    {{template "header.html" .}}
    
    <div class="container mx-auto px-4 py-8">
        <!-- 面包屑导航 -->
        <div class="mb-6">
            <div class="flex items-center text-sm text-gray-600">
                <a href="/nodes" class="hover:text-blue-600">节点管理</a>
                <svg class="w-4 h-4 mx-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                </svg>
                <a href="/nodes/{{ .node_id }}" id="breadcrumbNodeName" class="hover:text-blue-600">加载中...</a>
                <svg class="w-4 h-4 mx-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                </svg>
                <span class="text-gray-900 font-medium">反向代理</span>
            </div>
        </div>

        <!-- 页面标题 -->
        <div class="flex justify-between items-center mb-6">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">反向代理配置</h1>
                <p class="text-gray-600 mt-1" id="nodeNameDisplay">加载中...</p>
            </div>
            <div class="flex gap-2">
                <button onclick="refreshProxy()" class="px-3 py-1.5 text-xs font-medium text-gray-700 bg-gray-50 hover:bg-gray-100 border border-gray-200 rounded-lg transition flex items-center gap-1.5">
                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                    </svg>
                    刷新
                </button>
                <button onclick="showAddProxyModal()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition flex items-center gap-2">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                    </svg>
                    添加代理
                </button>
            </div>
        </div>

        <!-- 代理列表 -->
        <div class="bg-white rounded-lg border border-gray-200">
            <div id="proxyContent" class="p-4">
                <p class="text-center py-8 text-gray-500 text-xs">加载中...</p>
            </div>
        </div>
    </div>

    <!-- 添加代理模态框 -->
    <dialog id="addProxyModal" class="modal">
        <div class="modal-box">
            <h3 class="font-bold text-base mb-3">添加反向代理</h3>
            <form id="addProxyForm" class="space-y-3">
                <div class="form-control">
                    <label class="label"><span class="label-text">容器名称 *</span></label>
                    <select id="proxyContainer" required class="select select-bordered">
                        <option value="">选择容器</option>
                    </select>
                </div>
                <div class="form-control">
                    <label class="label"><span class="label-text">域名 *</span></label>
                    <input type="text" id="proxyDomain" required class="input input-bordered" placeholder="example.com">
                </div>
                <div class="form-control">
                    <label class="label"><span class="label-text">容器端口 *</span></label>
                    <input type="number" id="proxyPort" required min="1" max="65535" value="80" class="input input-bordered">
                </div>
                <div class="form-control">
                    <label class="label"><span class="label-text">描述</span></label>
                    <input type="text" id="proxyDescription" class="input input-bordered" placeholder="代理用途说明">
                </div>
                <hr class="my-4">
                <div class="form-control">
                    <label class="label cursor-pointer">
                        <span class="label-text font-semibold">启用 HTTPS (SSL/TLS)</span>
                        <input type="checkbox" id="sslEnabled" class="checkbox checkbox-primary">
                    </label>
                </div>
                <div id="sslOptions" style="display:none;" class="space-y-3">
                    <div class="form-control">
                        <label class="label"><span class="label-text">SSL 证书类型</span></label>
                        <select id="sslType" class="select select-bordered">
                            <option value="self-signed">自动生成自签名证书</option>
                            <option value="custom">手动填写证书内容</option>
                        </select>
                    </div>
                    <div id="customCertFields" style="display:none;" class="space-y-3">
                        <div class="form-control">
                            <label class="label"><span class="label-text">SSL 证书内容 *</span></label>
                            <textarea id="sslCert" class="textarea textarea-bordered" rows="4" placeholder="-----BEGIN CERTIFICATE-----&#10;...&#10;-----END CERTIFICATE-----"></textarea>
                        </div>
                        <div class="form-control">
                            <label class="label"><span class="label-text">SSL 私钥内容 *</span></label>
                            <textarea id="sslKey" class="textarea textarea-bordered" rows="4" placeholder="-----BEGIN PRIVATE KEY-----&#10;...&#10;-----END PRIVATE KEY-----"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-action">
                    <button type="button" onclick="closeProxyModal()" class="btn">取消</button>
                    <button type="submit" class="btn btn-primary">添加</button>
                </div>
            </form>
        </div>
        <form method="dialog" class="modal-backdrop"><button onclick="closeProxyModal()">close</button></form>
    </dialog>

    <script>
        const nodeId = parseInt({{ .node_id }});
        let containersData = [];

        $(document).ready(function() {
            loadNodeInfo();
            loadContainers();
            loadProxy();

            $('#addProxyForm').on('submit', function(e) {
                e.preventDefault();
                submitProxyForm();
            });

            $('#sslEnabled').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#sslOptions').slideDown(200);
                } else {
                    $('#sslOptions').slideUp(200);
                    $('#customCertFields').slideUp(200);
                }
            });

            $('#sslType').on('change', function() {
                if ($(this).val() === 'custom') {
                    $('#customCertFields').slideDown(200);
                } else {
                    $('#customCertFields').slideUp(200);
                    $('#sslCert').val('');
                    $('#sslKey').val('');
                }
            });
        });

        function loadNodeInfo() {
            $.get(`/api/nodes/${nodeId}`, function(result) {
                if (result.code === 200) {
                    $('#breadcrumbNodeName').text(result.data.name);
                    $('#nodeNameDisplay').text(result.data.name || '未知节点');
                }
            });
        }

        function loadContainers() {
            $.get(`/api/containers/cache?node_id=${nodeId}`, function(result) {
                if (result.code === 200) {
                    containersData = result.data || [];
                }
            });
        }

        function loadProxy() {
            $('#proxyContent').html('<p class="text-center py-8"><span class="loading loading-spinner loading-md"></span></p>');
            
            $.get(`/api/proxy-configs?node_id=${nodeId}`, function(result) {
                if (result.code === 200) {
                    renderProxy(result.data || []);
                } else {
                    $('#proxyContent').html('<p class="text-center py-8 text-error">加载失败</p>');
                }
            });
        }

        function renderProxy(data) {
            if (data.length === 0) {
                $('#proxyContent').html('<p class="text-center py-8 text-gray-500 text-xs">暂无反向代理配置</p>');
                return;
            }

            let html = '<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">';

            data.forEach(item => {
                const containerName = item.hostname || item.container_hostname;
                const sslEnabled = item.ssl_enabled || false;
                const sslType = item.ssl_type || 'none';
                
                let protocolBadge = '';
                if (sslEnabled) {
                    const sslTypeBadge = sslType === 'self-signed' ? 
                        '<span class="badge badge-warning badge-xs ml-1">自签</span>' : 
                        '<span class="badge badge-info badge-xs ml-1">自定义</span>';
                    protocolBadge = `<span class="badge badge-success badge-sm">HTTPS${sslTypeBadge}</span>`;
                } else {
                    protocolBadge = '<span class="badge badge-ghost badge-sm">HTTP</span>';
                }
                
                html += `
                    <div class="bg-white border border-gray-200 rounded-lg p-4 hover:border-blue-300 hover:shadow-md transition-all">
                        <div class="flex items-center justify-between mb-3">
                            <a href="/nodes/${nodeId}/containers/${containerName}" class="font-semibold text-gray-800 text-xs hover:text-blue-600 transition">
                                ${containerName}
                            </a>
                            <button onclick="deleteProxy(${item.id})" class="px-2 py-1 text-xs font-medium text-red-700 bg-red-50 hover:bg-red-100 border border-red-200 rounded transition">删除</button>
                        </div>
                        <div class="bg-gradient-to-br from-gray-50 to-gray-100 rounded-md p-3 mb-2 border border-gray-200">
                            <p class="text-xs text-gray-600 mb-1">域名</p>
                            <code class="text-xs font-mono text-gray-800 break-all block">${item.domain}</code>
                        </div>
                        <div class="flex items-center justify-between text-xs mb-2">
                            <span class="text-gray-600">端口</span>
                            <code class="px-2 py-0.5 text-xs font-medium font-mono text-gray-700 bg-gray-100 rounded">${item.container_port}</code>
                        </div>
                        <div class="flex items-center justify-between text-xs">
                            <span class="text-gray-600">协议</span>
                            ${protocolBadge}
                        </div>
                        ${item.description ? `<p class="text-xs text-gray-600 mt-2">${item.description}</p>` : ''}
                    </div>
                `;
            });

            html += '</div>';
            $('#proxyContent').html(html);
        }

        function showAddProxyModal() {
            const containers = containersData.map(c => `<option value="${c.hostname}">${c.hostname}</option>`).join('');
            $('#proxyContainer').html('<option value="">选择容器</option>' + containers);
            document.getElementById('addProxyModal').showModal();
        }

        function closeProxyModal() {
            document.getElementById('addProxyModal').close();
            $('#addProxyForm')[0].reset();
        }

        function submitProxyForm() {
            const sslEnabled = $('#sslEnabled').is(':checked');
            const sslType = $('#sslType').val();

            if (sslEnabled && sslType === 'custom') {
                const cert = $('#sslCert').val().trim();
                const key = $('#sslKey').val().trim();
                if (!cert || !key) {
                    showToast('error', '启用自定义SSL证书时，必须提供证书和私钥内容');
                    return;
                }
            }

            const data = {
                node_id: nodeId,
                container_hostname: $('#proxyContainer').val(),
                domain: $('#proxyDomain').val(),
                container_port: parseInt($('#proxyPort').val()),
                description: $('#proxyDescription').val(),
                ssl_enabled: sslEnabled,
                ssl_type: sslEnabled ? sslType : 'none'
            };

            if (sslEnabled && sslType === 'custom') {
                data.ssl_cert = $('#sslCert').val();
                data.ssl_key = $('#sslKey').val();
            }

            $.ajax({
                url: '/api/proxy-configs',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(result) {
                    if (result.code === 200) {
                        showToast('success', '反向代理添加成功');
                        closeProxyModal();
                        loadProxy();
                    } else {
                        showToast('error', result.msg);
                    }
                }
            });
        }

        function deleteProxy(id) {
            if (!confirm('确定要删除此反向代理配置吗？')) return;
            
            $.ajax({
                url: `/api/proxy-configs/${id}`,
                type: 'DELETE',
                success: function(result) {
                    if (result.code === 200) {
                        showToast('success', '删除成功');
                        loadProxy();
                    } else {
                        showToast('error', result.msg);
                    }
                }
            });
        }

        function refreshProxy() {
            loadProxy();
        }

        function showToast(type, message) {
            const colors = {
                'success': 'bg-green-600',
                'error': 'bg-red-600',
                'info': 'bg-blue-600'
            };
            
            const toast = $(`
                <div class="fixed top-4 right-4 ${colors[type] || colors.info} text-white px-6 py-3 rounded-lg shadow-lg z-50">
                    ${message}
                </div>
            `);
            
            $('body').append(toast);
            
            setTimeout(() => {
                toast.fadeOut(300, function() { $(this).remove(); });
            }, 3000);
        }
    </script>

    {{template "footer.html" .}}
</body>
</html>

